<template>
  <div class="auth-content" v-if="invalid">
    <span>丢失appId或redirectUrl参数</span>
  </div>
  <div class="auth-content" v-else>
    <div class="auth-box" v-if="userInfo">
      <span class="user-account">{{userInfo.userAccount}}</span>
      <div class="auth-btn">
        <el-button type="primary" :loading="authLoading" @click="handleAuth">授权登录</el-button>
      </div>
      <div class="auth-btn">
        <el-button type="primary" link @click="handleGotoLogin">切换账号</el-button>
      </div>
      <p class="tip">点击授权登录即代表您同意使用该账号登录第三方系统</p>
    </div>
    <p v-else>页面加载中……</p>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {useRouter, useRoute} from "vue-router";
import common from "~/common/common.js";
import api from "~/api/index.js";
const route = useRoute()
const router = useRouter()
const redirectUrl = decodeURIComponent(route.query.redirectUrl || route.query.redirecturl || route.query.redirect_url || '')
const appId = route.query.appId || route.query.appid || route.query.app_id || ''

const invalid = ref(!redirectUrl || !appId)
const userInfo = ref(null)
const user = common.getLocalUser()
const userId = user.userId
const authLoading = ref(false)
const getUserInfo = async () => {
  try {
    const res = await api.getUserInfo(user.userId)
    if (res.data) {
      userInfo.value = res.data
    }
  } catch(e){}
}
const getCode = async () => {
  let code = ''
  try {
    const res = await api.getAuthCode({appId, userId})
    if (res.data) {
      code = res.data
    }
  } catch(e){}
  return code
}
const handleAuth = async () => {
  authLoading.value = true
  try {
    const code = await getCode()
    if (code) {
      let url = ''
      if (redirectUrl.indexOf('?') > -1) {
        url = `${redirectUrl}&code=${code}`
      } else {
        url = `${redirectUrl}?code=${code}`
      }
      window.top.location.href = url
    }
    authLoading.value = false
  } catch(e){
    authLoading.value = false
  }

}
const handleGotoLogin = () => {
  router.replace(`/login?appId=${appId}&redirectUrl=${encodeURIComponent(redirectUrl)}`)
}
onMounted(async () => {
  if (!appId || !redirectUrl) {
    return
  }
  await getUserInfo()
  if (userInfo.value) {

  } else {
    router.replace(`/login?appId=${appId}&redirectUrl=${encodeURIComponent(redirectUrl)}`)
  }
})
</script>

<style scoped lang="scss">
.auth-content{
  text-align: center;
  margin: 60px 0;
  font-size: 14px;
}
.user-account{
  padding: 2px 10px;
  background: #f7f7f7;
  border-radius: 3px;
  margin-bottom: 15px;
}
.auth-box{
  /*display: inline-flex;*/
  /*flex-direction: column;*/
  /*justify-content: center;*/
  .auth-btn{
    text-align: center;
    margin-top: 20px;
  }
}
.tip{
  font-size: 12px;
  color: #999;
  padding-top: 10px;
}
</style>
